<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>艺术品交易与溯源系统</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome图标 -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        .fade-in { animation: fadeIn 0.5s ease-in; }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        .card { box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .art-card { height: 320px; }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <!-- 顶部导航栏（登录后显示） -->
    <header id="main-header" class="bg-indigo-600 text-white p-4 shadow-md hidden">
        <div class="container mx-auto flex justify-between items-center">
            <h1 class="text-xl font-bold">
                <i class="fa fa-paint-brush mr-2"></i>艺术品交易与溯源系统
            </h1>
            <div class="flex items-center">
                <span id="buyer-username" class="mr-4">欢迎，用户</span>
                <button onclick="logout()" class="bg-red-500 hover:bg-red-600 px-3 py-1 rounded">
                    <i class="fa fa-sign-out mr-1"></i>退出登录
                </button>
            </div>
        </div>
        <!-- 买家二级导航栏 -->
        <nav class="bg-indigo-700 text-white px-4 py-2">
            <div class="container mx-auto flex space-x-6">
                <a href="javascript:showBuyerPage('home')" class="hover:underline">首页</a>
                <a href="javascript:showBuyerPage('search')" class="hover:underline">艺术品查询</a>
                <a href="javascript:showBuyerPage('collection')" class="hover:underline">我的收藏</a>
                <a href="javascript:showBuyerPage('transaction')" class="hover:underline">我的交易</a>
                <a href="javascript:showBuyerPage('trace')" class="hover:underline">溯源查询</a>
                <a href="javascript:showBuyerPage('profile')" class="hover:underline">个人中心</a>
            </div>
        </nav>
    </header>

    <main class="container mx-auto p-4 md:p-8">
        <!-- 1. 登录界面 -->
        <div id="login-page" class="fade-in">
            <div class="flex flex-col md:flex-row h-screen">
                <!-- 左侧：登录表单 -->
                <div class="w-full md:w-1/2 flex flex-col justify-center items-center p-8 bg-white">
                    <div class="text-center mb-8">
                        <i class="fa fa-paint-brush text-4xl text-indigo-600 mb-2"></i>
                        <h1 class="text-2xl font-bold">艺术品交易与溯源系统</h1>
                    </div>
                    <form id="loginForm" class="w-full max-w-md bg-white p-6 rounded-lg card">
                        <div class="mb-4">
                            <label class="block text-gray-600 mb-2" for="login-username">用户名</label>
                            <input type="text" id="login-username" 
                                class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-indigo-500"
                                placeholder="请输入用户名" required>
                        </div>
                        <div class="mb-4">
                            <label class="block text-gray-600 mb-2" for="login-password">密码</label>
                            <input type="password" id="login-password" 
                                class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-indigo-500"
                                placeholder="请输入密码" required>
                        </div>
                        <div class="flex items-center mb-6">
                            <input type="checkbox" id="remember-pwd" class="mr-2">
                            <label for="remember-pwd" class="text-gray-600">记住密码</label>
                            <a href="#" class="ml-auto text-indigo-600 hover:underline">忘记密码</a>
                        </div>
                        <button type="submit" 
                            class="w-[80%] mx-auto bg-indigo-600 hover:bg-indigo-700 text-white py-2 px-4 rounded transition duration-200">
                            登录
                        </button>
                        <p class="text-center mt-4 text-gray-500">
                            还没有账号？<a href="javascript:showTab('register')" class="text-indigo-600 hover:underline">立即注册</a>
                        </p>
                    </form>
                </div>
                <!-- 右侧：辅助区域 -->
                <div class="w-full md:w-1/2 bg-indigo-50 flex flex-col justify-center p-8 hidden md:flex">
                    <h2 class="text-xl font-semibold mb-4 text-gray-700">系统功能简介</h2>
                    <div class="space-y-4 mb-6">
                        <div class="flex items-start">
                            <i class="fa fa-shopping-cart text-indigo-600 mr-3 mt-1"></i>
                            <div>
                                <h3 class="font-medium">艺术品交易</h3>
                                <p class="text-gray-600 text-sm">安全可靠的艺术品在线交易流程，保障买卖双方权益</p>
                            </div>
                        </div>
                        <div class="flex items-start">
                            <i class="fa fa-history text-indigo-600 mr-3 mt-1"></i>
                            <div>
                                <h3 class="font-medium">溯源查询</h3>
                                <p class="text-gray-600 text-sm">记录艺术品全生命周期轨迹，可追溯来源与流转历史</p>
                            </div>
                        </div>
                        <div class="flex items-start">
                            <i class="fa fa-star text-indigo-600 mr-3 mt-1"></i>
                            <div>
                                <h3 class="font-medium">收藏管理</h3>
                                <p class="text-gray-600 text-sm">便捷管理个人收藏，实时跟踪艺术品价值变化</p>
                            </div>
                        </div>
                    </div>
                    <div class="flex items-center">
                        <i class="fa fa-headphones text-indigo-600 mr-3"></i>
                        <span class="text-gray-600">客服联系方式：400-123-4567</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 2. 注册界面 -->
        <div id="register-page" class="hidden fade-in">
            <div class="container mx-auto p-8">
                <div class="flex justify-between items-center mb-6">
                    <button onclick="showTab('login')" class="text-indigo-600 hover:underline">
                        <i class="fa fa-arrow-left mr-1"></i>返回登录
                    </button>
                    <h2 class="text-2xl font-bold">用户注册</h2>
                    <div></div>
                </div>
                <form id="registerForm" class="bg-white p-6 rounded-lg card">
                    <!-- 第一步：选择用户角色 -->
                    <div class="mb-6 p-4 border border-gray-200 rounded-lg">
                        <h3 class="text-lg font-semibold mb-4 text-gray-700">第一步：选择用户角色</h3>
                        <div class="flex space-x-6">
                            <label class="inline-flex items-center text-lg">
                                <input type="radio" name="user-role" value="买家" checked class="mr-2 text-indigo-600">买家
                            </label>
                            <label class="inline-flex items-center text-lg">
                                <input type="radio" name="user-role" value="卖家" class="mr-2 text-indigo-600">卖家
                            </label>
                        </div>
                    </div>
                    <!-- 第二步：填写注册信息 -->
                    <div class="mb-6 p-4 border border-gray-200 rounded-lg">
                        <h3 class="text-lg font-semibold mb-4 text-gray-700">第二步：填写注册信息</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label class="block text-gray-600 mb-2" for="reg-username">用户名 <span class="text-red-500">*</span></label>
                                <input type="text" id="reg-username" 
                                    class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-indigo-500"
                                    placeholder="请输入用户名" required>
                            </div>
                            <div>
                                <label class="block text-gray-600 mb-2" for="reg-realname">真实姓名 <span class="text-red-500">*</span></label>
                                <input type="text" id="reg-realname" 
                                    class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-indigo-500"
                                    placeholder="请输入真实姓名" required>
                            </div>
                            <div>
                                <label class="block text-gray-600 mb-2" for="reg-password">密码 <span class="text-red-500">*</span></label>
                                <input type="password" id="reg-password" 
                                    class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-indigo-500"
                                    placeholder="请输入密码（至少6位）" required>
                            </div>
                            <div>
                                <label class="block text-gray-600 mb-2" for="reg-confirm-pwd">确认密码 <span class="text-red-500">*</span></label>
                                <input type="password" id="reg-confirm-pwd" 
                                    class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-indigo-500"
                                    placeholder="请确认密码" required>
                            </div>
                            <div>
                                <label class="block text-gray-600 mb-2" for="reg-contact">联系方式 <span class="text-red-500">*</span></label>
                                <input type="text" id="reg-contact" 
                                    class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-indigo-500"
                                    placeholder="请输入手机号或邮箱" required>
                            </div>
                            <div>
                                <label class="block text-gray-600 mb-2" for="reg-address">地址</label>
                                <input type="text" id="reg-address" 
                                    class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-indigo-500"
                                    placeholder="请输入联系地址">
                            </div>
                        </div>
                    </div>
                    <!-- 第三步：提交审核 -->
                    <div class="mb-6 text-center">
                        <button type="submit" 
                            class="bg-indigo-600 hover:bg-indigo-700 text-white py-2 px-8 rounded transition duration-200">
                            提交注册
                        </button>
                        <p id="audit-tip" class="mt-2 text-gray-500 text-sm hidden">审核中，请等待管理员审核</p>
                    </div>
                    <!-- 注册须知 -->
                    <div class="text-gray-500 text-sm">
                        <p>注册须知：请仔细阅读 <a href="#" class="text-indigo-600 hover:underline">《艺术品交易系统用户协议》</a>，提交注册即表示同意协议条款</p>
                    </div>
                </form>
            </div>
        </div>

        <!-- 3. 买家首页 -->
        <div id="buyer-home" class="hidden fade-in">
            <div class="flex flex-col md:flex-row gap-6">
                <!-- 左侧：分类筛选栏 -->
                <div class="w-full md:w-1/4 lg:w-1/5 p-4 bg-white rounded-lg card">
                    <h3 class="text-lg font-semibold mb-4 text-gray-700">分类筛选</h3>
                    <!-- 艺术品类别 -->
                    <div class="mb-6">
                        <h4 class="font-medium mb-2 text-gray-600">艺术品类别</h4>
                        <div class="flex flex-col space-y-3">
                            <label class="inline-flex items-center">
                                <input type="checkbox" class="mr-2 text-indigo-600" onchange="filterArtworks()">绘画
                            </label>
                            <label class="inline-flex items-center">
                                <input type="checkbox" class="mr-2 text-indigo-600" onchange="filterArtworks()">雕塑
                            </label>
                            <label class="inline-flex items-center">
                                <input type="checkbox" class="mr-2 text-indigo-600" onchange="filterArtworks()">书法
                            </label>
                            <label class="inline-flex items-center">
                                <input type="checkbox" class="mr-2 text-indigo-600" onchange="filterArtworks()">陶瓷
                            </label>
                            <label class="inline-flex items-center">
                                <input type="checkbox" class="mr-2 text-indigo-600" onchange="filterArtworks()">其他
                            </label>
                        </div>
                    </div>
                    <!-- 创作年代 -->
                    <div class="mb-6">
                        <h4 class="font-medium mb-2 text-gray-600">创作年代</h4>
                        <div class="flex flex-col space-y-3">
                            <label class="inline-flex items-center">
                                <input type="checkbox" class="mr-2 text-indigo-600" onchange="filterArtworks()">古代（1840年前）
                            </label>
                            <label class="inline-flex items-center">
                                <input type="checkbox" class="mr-2 text-indigo-600" onchange="filterArtworks()">近代（1840-1949）
                            </label>
                            <label class="inline-flex items-center">
                                <input type="checkbox" class="mr-2 text-indigo-600" onchange="filterArtworks()">现代（1949-2000）
                            </label>
                            <label class="inline-flex items-center">
                                <input type="checkbox" class="mr-2 text-indigo-600" onchange="filterArtworks()">当代（2000年后）
                            </label>
                        </div>
                    </div>
                    <!-- 价格区间 -->
                    <div>
                        <h4 class="font-medium mb-2 text-gray-600">价格区间</h4>
                        <div class="flex flex-col space-y-3">
                            <label class="inline-flex items-center">
                                <input type="checkbox" class="mr-2 text-indigo-600" onchange="filterArtworks()">0-10,000元
                            </label>
                            <label class="inline-flex items-center">
                                <input type="checkbox" class="mr-2 text-indigo-600" onchange="filterArtworks()">10,000-50,000元
                            </label>
                            <label class="inline-flex items-center">
                                <input type="checkbox" class="mr-2 text-indigo-600" onchange="filterArtworks()">50,000-100,000元
                            </label>
                            <label class="inline-flex items-center">
                                <input type="checkbox" class="mr-2 text-indigo-600" onchange="filterArtworks()">100,000元以上
                            </label>
                        </div>
                    </div>
                </div>
                <!-- 中间：艺术品列表 -->
                <div class="w-full md:w-3/4 lg:w-3/5 p-4">
    <h2 class="text-xl font-bold mb-6 text-gray-800">艺术品列表</h2>
    <div id="artworks-container" class="grid grid-cols-1 sm:grid-cols-2 gap-6">
        <!-- 艺术品卡片将通过JS动态生成 -->
    </div>
</div>
<!-- 右侧：热门推荐区 -->
<div class="w-full md:w-1/4 lg:w-1/5 p-4 bg-white rounded-lg card">
    <h3 class="text-lg font-semibold mb-4 text-gray-700">热门推荐</h3>
    <div id="hot-recommendations" class="space-y-4">
        <!-- 热门艺术品将通过JS动态生成 -->
    </div>
    <button class="w-full mt-4 bg-indigo-100 hover:bg-indigo-200 text-indigo-600 py-2 rounded transition duration-200">
        查看更多
    </button>
</div>
</div>
</div>

<!-- 4. 艺术品详情与溯源界面 -->
<div id="art-detail" class="hidden fade-in">
    <h2 class="text-xl font-bold mb-6 text-gray-800">艺术品详情与溯源</h2>
    <div class="flex flex-col lg:flex-row gap-6">
        <!-- 左侧：艺术品展示区 -->
        <div class="w-full lg:w-1/3 p-4 bg-white rounded-lg card">
            <div class="relative">
                <img id="art-main-img" src="https://picsum.photos/600/800?random=5" alt="艺术品主图" class="w-full h-80 object-cover rounded">
                <button id="zoom-btn" class="absolute bottom-2 right-2 bg-black bg-opacity-50 text-white p-2 rounded-full">
                    <i class="fa fa-search-plus"></i>
                </button>
            </div>
            <div class="flex flex-wrap gap-2 mt-3">
                <img src="https://picsum.photos/120/120?random=6" alt="细节图1" class="w-20 h-20 object-cover rounded cursor-pointer hover:ring-2 hover:ring-indigo-500" onclick="changeMainImg(this.src)">
                <img src="https://picsum.photos/120/120?random=7" alt="细节图2" class="w-20 h-20 object-cover rounded cursor-pointer hover:ring-2 hover:ring-indigo-500" onclick="changeMainImg(this.src)">
                <img src="https://picsum.photos/120/120?random=8" alt="细节图3" class="w-20 h-20 object-cover rounded cursor-pointer hover:ring-2 hover:ring-indigo-500" onclick="changeMainImg(this.src)">
                <img src="https://picsum.photos/120/120?random=9" alt="细节图4" class="w-20 h-20 object-cover rounded cursor-pointer hover:ring-2 hover:ring-indigo-500" onclick="changeMainImg(this.src)">
            </div>
        </div>
        <!-- 中间：艺术品基础信息 -->
        <div class="w-full lg:w-1/3 p-4 bg-white rounded-lg card">
            <h3 id="art-name" class="text-xl font-semibold mb-2">艺术品名称</h3>
            <div class="flex flex-wrap gap-2 mb-4">
                <span class="bg-indigo-100 text-indigo-600 text-xs px-2 py-1 rounded" id="art-category">类别</span>
                <span class="bg-gray-100 text-gray-600 text-xs px-2 py-1 rounded" id="art-era">年代</span>
            </div>
            <div class="space-y-3 mb-6">
                <p class="text-gray-600"><span class="font-medium">尺寸：</span><span id="art-size">--</span></p>
                <p class="text-gray-600"><span class="font-medium">材质：</span><span id="art-material">--</span></p>
                <p class="text-gray-600"><span class="font-medium">创作背景：</span><span id="art-background">--</span></p>
                <p class="text-gray-600"><span class="font-medium">创作者：</span><a href="#" class="text-indigo-600 hover:underline" id="artist-link">--</a></p>
            </div>
            <div class="border-t pt-4">
                <h4 class="font-medium mb-2">作品简介</h4>
                <p class="text-gray-600 text-sm" id="art-description">加载中...</p>
            </div>
        </div>
        <!-- 右侧：交易操作区 -->
        <div class="w-full lg:w-1/3 p-4 bg-white rounded-lg card">
            <div class="border-b pb-4 mb-4">
                <p class="text-gray-600 mb-1">卖家信息</p>
                <div class="flex items-center">
                    <img src="https://picsum.photos/40/40?random=20" alt="卖家头像" class="w-10 h-10 rounded-full mr-2">
                    <div>
                        <p id="seller-name" class="font-medium">卖家名称</p>
                        <div class="flex text-yellow-400 text-xs">
                            <i class="fa fa-star"></i>
                            <i class="fa fa-star"></i>
                            <i class="fa fa-star"></i>
                            <i class="fa fa-star"></i>
                            <i class="fa fa-star-half-o"></i>
                            <span class="text-gray-500 ml-1">(4.5)</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="mb-6">
                <p class="text-gray-500 text-sm mb-1">价格</p>
                <p class="text-3xl text-indigo-600 font-bold" id="art-price">¥0.00</p>
            </div>
            <div class="space-y-3">
                <button id="buy-now-btn" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white py-3 px-4 rounded transition duration-200">
                    立即购买
                </button>
                <button id="add-collection-btn" class="w-full bg-gray-100 hover:bg-gray-200 text-gray-800 py-3 px-4 rounded transition duration-200">
                    <i class="fa fa-heart-o mr-1"></i>加入收藏
                </button>
                <button id="contact-seller-btn" class="w-full bg-white border border-gray-300 hover:bg-gray-50 text-gray-800 py-2 px-4 rounded transition duration-200">
                    <i class="fa fa-comments-o mr-1"></i>联系卖家
                </button>
            </div>
        </div>
    </div>
    <!-- 底部：溯源信息区 -->
    <div class="mt-6 p-4 bg-white rounded-lg card">
        <h3 class="text-lg font-semibold mb-4 text-gray-700">溯源轨迹</h3>
        <div id="trace-container" class="space-y-6">
            <!-- 溯源记录将通过JS动态生成 -->
            <div class="flex">
                <div class="mr-4 flex flex-col items-center">
                    <div class="w-3 h-3 rounded-full bg-indigo-600"></div>
                    <div class="w-0.5 h-full bg-gray-200 mt-1"></div>
                </div>
                <div>
                    <p class="font-medium text-indigo-600">加载中...</p>
                    <p class="text-gray-500 text-sm mt-1">请稍候，正在获取溯源信息</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 5. 我的交易界面 -->
<div id="my-transaction" class="hidden fade-in">
    <h2 class="text-xl font-bold mb-6 text-gray-800">我的交易</h2>
    <!-- 交易状态筛选 -->
    <div class="flex flex-wrap gap-2 mb-6">
        <button class="px-4 py-2 bg-indigo-600 text-white rounded" onclick="filterTransactions('all')">全部</button>
        <button class="px-4 py-2 bg-gray-100 text-gray-600 rounded hover:bg-gray-200" onclick="filterTransactions('pending_payment')">待付款</button>
        <button class="px-4 py-2 bg-gray-100 text-gray-600 rounded hover:bg-gray-200" onclick="filterTransactions('pending_delivery')">待收货</button>
        <button class="px-4 py-2 bg-gray-100 text-gray-600 rounded hover:bg-gray-200" onclick="filterTransactions('completed')">交易完成</button>
        <button class="px-4 py-2 bg-gray-100 text-gray-600 rounded hover:bg-gray-200" onclick="filterTransactions('cancelled')">已取消</button>
    </div>
    <!-- 交易列表 -->
    <div class="bg-white rounded-lg overflow-hidden card">
        <table class="w-full">
            <thead>
                <tr class="bg-gray-50">
                    <th class="px-4 py-3 text-left">交易ID</th>
                    <th class="px-4 py-3 text-left">艺术品</th>
                    <th class="px-4 py-3 text-left">卖家</th>
                    <th class="px-4 py-3 text-left">交易时间</th>
                    <th class="px-4 py-3 text-left">交易金额</th>
                    <th class="px-4 py-3 text-left">交易状态</th>
                    <th class="px-4 py-3 text-left">操作</th>
                </tr>
            </thead>
            <tbody id="transactions-table-body">
                <!-- 交易记录将通过JS动态生成 -->
                <tr>
                    <td colspan="7" class="px-4 py-8 text-center text-gray-500">
                        <i class="fa fa-exchange text-2xl mb-2 block"></i>
                        暂无交易记录
                    </td>
                </tr>
            </tbody>
        </table>
        
        <!-- 分页控件 -->
        <div id="pagination" class="px-4 py-3 flex items-center justify-between border-t bg-gray-50 hidden">
            <div class="flex-1 flex justify-between sm:hidden">
                <button id="prev-page-mobile" class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                    上一页
                </button>
                <button id="next-page-mobile" class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
                    下一页
                </button>
            </div>
            <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                <div>
                    <p class="text-sm text-gray-700">
                        显示第 <span id="current-page" class="font-medium">1</span> 到 <span id="last-shown" class="font-medium">1</span> 条，共 <span id="total-records" class="font-medium">0</span> 条记录
                    </p>
                </div>
                <div>
                    <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                        <button id="prev-page" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                            <span class="sr-only">上一页</span>
                            <i class="fa fa-chevron-left text-xs"></i>
                        </button>
                        <div id="page-numbers" class="flex">
                            <!-- 页码将通过JS动态生成 -->
                        </div>
                        <button id="next-page" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                            <span class="sr-only">下一页</span>
                            <i class="fa fa-chevron-right text-xs"></i>
                        </button>
                    </nav>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 其他买家页面（搜索、收藏、溯源查询、个人中心）占位 -->
<div id="buyer-search" class="hidden fade-in">
    <h2 class="text-xl font-bold mb-6 text-gray-800">艺术品查询</h2>
    <!-- 搜索功能实现 -->
    <div class="bg-white p-6 rounded-lg card mb-6">
        <div class="flex flex-col md:flex-row gap-4">
            <input type="text" placeholder="输入艺术品名称或创作者" class="flex-1 px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-indigo-500">
            <button class="bg-indigo-600 hover:bg-indigo-700 text-white py-2 px-6 rounded transition duration-200">
                <i class="fa fa-search mr-1"></i>搜索
            </button>
        </div>
    </div>
    <div class="text-center py-10 text-gray-500">
        <i class="fa fa-search text-4xl mb-2"></i>
        <p>请输入关键词搜索艺术品</p>
    </div>
</div>

<div id="buyer-collection" class="hidden fade-in">
    <h2 class="text-xl font-bold mb-6 text-gray-800">我的收藏</h2>
    <div class="text-center py-10 text-gray-500">
        <i class="fa fa-heart-o text-4xl mb-2"></i>
        <p>您还没有收藏任何艺术品</p>
    </div>
</div>

<div id="buyer-trace" class="hidden fade-in">
    <h2 class="text-xl font-bold mb-6 text-gray-800">溯源查询</h2>
    <div class="bg-white p-6 rounded-lg card mb-6">
        <div class="flex flex-col md:flex-row gap-4">
            <input type="text" placeholder="输入艺术品ID或名称" class="flex-1 px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-indigo-500">
            <button class="bg-indigo-600 hover:bg-indigo-700 text-white py-2 px-6 rounded transition duration-200">
                <i class="fa fa-history mr-1"></i>查询溯源
            </button>
        </div>
    </div>
    <div class="text-center py-10 text-gray-500">
        <i class="fa fa-barcode text-4xl mb-2"></i>
        <p>请输入艺术品信息查询溯源记录</p>
    </div>
</div>

<div id="buyer-profile" class="hidden fade-in">
    <h2 class="text-xl font-bold mb-6 text-gray-800">个人中心</h2>
    <div class="bg-white p-6 rounded-lg card">
        <div class="flex flex-col md:flex-row gap-6">
            <div class="w-full md:w-1/3">
                <div class="text-center">
                    <img src="https://picsum.photos/120/120?random=30" alt="用户头像" class="w-32 h-32 rounded-full mx-auto mb-4">
                    <h3 id="profile-username" class="text-xl font-medium">用户名</h3>
                    <p id="profile-role" class="text-gray-500">买家</p>
                </div>
            </div>
            <div class="w-full md:w-2/3">
                <h4 class="font-medium mb-4 pb-2 border-b">个人信息</h4>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <p class="text-gray-500 text-sm">真实姓名</p>
                        <p id="profile-realname" class="font-medium">--</p>
                    </div>
                    <div>
                        <p class="text-gray-500 text-sm">联系方式</p>
                        <p id="profile-contact" class="font-medium">--</p>
                    </div>
                    <div class="md:col-span-2">
                        <p class="text-gray-500 text-sm">联系地址</p>
                        <p id="profile-address" class="font-medium">--</p>
                    </div>
                </div>
                <button class="mt-6 bg-gray-100 hover:bg-gray-200 text-gray-800 py-2 px-4 rounded transition duration-200">
                    <i class="fa fa-pencil mr-1"></i>编辑资料
                </button>
            </div>
        </div>
    </div>
</div>
</main>

<script>
// 全局变量
let currentUser = null;
let currentArtwork = null;
let artworksData = [];
let transactionsData = [];

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', () => {
    // 绑定表单提交事件
    document.getElementById('registerForm').addEventListener('submit', handleRegister);
    document.getElementById('loginForm').addEventListener('submit', handleLogin);
    
    // 从本地存储恢复登录状态
    const savedUser = localStorage.getItem('currentUser');
    if (savedUser) {
        currentUser = JSON.parse(savedUser);
        updateUserUI();
        fetchArtworks();
        fetchTransactions();
    } else {
        // 未登录状态下显示登录页
        showTab('login');
    }
});

// 切换登录/注册界面
function showTab(tabName) {
    if (tabName === 'login') {
        document.getElementById('login-page').classList.remove('hidden');
        document.getElementById('register-page').classList.remove('fade-in');
        document.getElementById('register-page').classList.add('hidden');
        document.getElementById('login-page').classList.add('fade-in');
    } else if (tabName === 'register') {
        document.getElementById('login-page').classList.add('hidden');
        document.getElementById('register-page').classList.remove('hidden');
        document.getElementById('register-page').classList.add('fade-in');
    }
}

// 切换买家页面
function showBuyerPage(pageName) {
    // 隐藏所有买家页面
    document.getElementById('buyer-home').classList.add('hidden');
    document.getElementById('buyer-search').classList.add('hidden');
    document.getElementById('buyer-collection').classList.add('hidden');
    document.getElementById('my-transaction').classList.add('hidden');
    document.getElementById('buyer-trace').classList.add('hidden');
    document.getElementById('buyer-profile').classList.add('hidden');
    document.getElementById('art-detail').classList.add('hidden');
    
    // 显示目标页面
    document.getElementById(pageName === 'transaction' ? 'my-transaction' : `buyer-${pageName}`).classList.remove('hidden');
    document.getElementById(pageName === 'transaction' ? 'my-transaction' : `buyer-${pageName}`).classList.add('fade-in');
}

// 处理注册
async function handleRegister(e) {
    e.preventDefault();
    const password = document.getElementById('reg-password').value;
    const confirmPwd = document.getElementById('reg-confirm-pwd').value;
    
    // 前端验证
    if (password !== confirmPwd) {
        alert('两次输入的密码不一致');
        return;
    }
    if (password.length < 6) {
        alert('密码长度不能少于6位');
        return;
    }
    
    const data = {
        username: document.getElementById('reg-username').value,
        password: password,
        real_name: document.getElementById('reg-realname').value,
        contact_info: document.getElementById('reg-contact').value,
        address: document.getElementById('reg-address').value,
        user_role: document.querySelector('input[name="user-role"]:checked').value
    };

    try {
        const response = await fetch('http://localhost:5000/register', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
        const result = await response.json();
        
        if (result.success) {
            // 显示审核提示
            document.getElementById('audit-tip').classList.remove('hidden');
            // 2秒后自动跳转登录页
            setTimeout(() => {
                showTab('login');
                document.getElementById('registerForm').reset();
                document.getElementById('audit-tip').classList.add('hidden');
            }, 2000);
        } else {
            alert('注册失败：' + (result.error || '用户名可能已存在'));
        }
    } catch (error) {
        console.error('注册失败：', error);
        alert('注册失败，请检查后端服务是否启动');
    }
}

// 处理登录
async function handleLogin(e) {
    e.preventDefault();
    const data = {
        username: document.getElementById('login-username').value,
        password: document.getElementById('login-password').value
    };

    try {
        // 调用登录接口验证账号密码
        const loginResponse = await fetch('http://localhost:5000/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
        const loginResult = await loginResponse.json();

        if (loginResult.authenticated) {
            // 登录成功后获取用户详情
            const userResponse = await fetch(`http://localhost:5000/user?username=${encodeURIComponent(data.username)}`);
            const userInfo = await userResponse.json();

            if (userInfo && userInfo.user_id) {
                // 保存用户信息并更新UI
                currentUser = userInfo;
                localStorage.setItem('currentUser', JSON.stringify(currentUser));
                updateUserUI();
                fetchArtworks();
                fetchTransactions();
                showBuyerPage('home');
            } else {
                alert('登录失败：获取用户信息失败');
            }
        } else {
            // 密码错误或用户不存在
            alert('登录失败：用户名或密码错误');
        }
    } catch (error) {
        console.error('登录失败：', error);
        alert('登录失败，请检查后端服务是否启动');
    }
}

// 退出登录
function logout() {
    if (confirm('确定要退出登录吗？')) {
        currentUser = null;
        localStorage.removeItem('currentUser');
        updateUserUI();
        showTab('login');
    }
}

// 更新用户状态UI
function updateUserUI() {
    const mainHeader = document.getElementById('main-header');
    const buyerUsername = document.getElementById('buyer-username');
    const profileUsername = document.getElementById('profile-username');
    const profileRealname = document.getElementById('profile-realname');
    const profileContact = document.getElementById('profile-contact');
    const profileAddress = document.getElementById('profile-address');
    
    if (currentUser) {
        // 显示头部导航
        mainHeader.classList.remove('hidden');
        // 更新用户名显示
        buyerUsername.textContent = `欢迎，${currentUser.username}`;
        profileUsername.textContent = currentUser.username;
        profileRealname.textContent = currentUser.real_name || '--';
        profileContact.textContent = currentUser.contact_info || '--';
        profileAddress.textContent = currentUser.address || '--';
    } else {
        // 隐藏头部导航
        mainHeader.classList.add('hidden');
    }
}

// 获取艺术品列表
async function fetchArtworks() {
    try {
        const response = await fetch('http://localhost:5000/artworks');
        artworksData = await response.json();
        renderArtworks(artworksData);
        renderHotRecommendations(artworksData.slice(0, 5)); // 取前5个作为热门推荐
    } catch (error) {
        console.error('获取艺术品失败：', error);
        document.getElementById('artworks-container').innerHTML = `
            <div class="text-center text-red-500 py-10 col-span-full">
                <i class="fa fa-exclamation-circle text-2xl mb-2"></i>
                <p>加载艺术品失败，请稍后重试</p>
            </div>
        `;
    }
}

// 渲染艺术品列表
function renderArtworks(artworks) {
    const container = document.getElementById('artworks-container');
    if (artworks.length === 0) {
        container.innerHTML = `
            <div class="text-center text-gray-500 py-10 col-span-full">
                <i class="fa fa-picture-o text-4xl mb-2"></i>
                <p>暂无艺术品，敬请期待</p>
            </div>
        `;
        return;
    }

    container.innerHTML = artworks.map(art => `
        <div class="bg-white rounded-lg overflow-hidden card art-card hover:shadow-lg transition-shadow">
            <img src="https://picsum.photos/400/300?random=${art.artwork_id}" alt="${art.title}" class="w-full h-48 object-cover">
            <div class="p-4">
                <h3 class="font-semibold text-lg mb-1 line-clamp-1">${art.title}</h3>
                <p class="text-gray-600 text-sm mb-2">创作者：${art.creator}</p>
                <p class="text-gray-500 text-sm mb-3 line-clamp-2">${art.description || '无描述'}</p>
                <div class="flex justify-between items-center">
                    <span class="text-indigo-600 font-bold">¥${parseFloat(art.price).toFixed(2)}</span>
                    <span class="text-xs text-gray-400">${formatDate(art.create_time)}</span>
                </div>
                <div class="flex space-x-2 mt-3">
                    <button class="flex-1 text-sm bg-indigo-100 text-indigo-600 px-2 py-1 rounded hover:bg-indigo-200"
                            onclick="showArtDetail(${art.artwork_id})">查看详情</button>
                    <button class="flex-1 text-sm bg-gray-100 text-gray-600 px-2 py-1 rounded hover:bg-gray-200"
                            onclick="addToCollection(${art.artwork_id})">加入收藏</button>
                </div>
            </div>
        </div>
    `).join('');
}

// 渲染热门推荐
function renderHotRecommendations(artworks) {
    const container = document.getElementById('hot-recommendations');
    container.innerHTML = artworks.map(art => `
        <div class="flex items-center p-2 hover:bg-gray-50 rounded transition-colors">
            <img src="https://picsum.photos/100/100?random=${art.artwork_id}" alt="${art.title}" class="w-16 h-16 object-cover rounded mr-3">
            <div class="flex-1 min-w-0">
                <h4 class="font-medium text-sm line-clamp-1">${art.title}</h4>
                <p class="text-gray-600 text-xs line-clamp-1">${art.creator}</p>
                <p class="text-indigo-600 text-xs">¥${parseFloat(art.price).toFixed(2)}</p>
            </div>
        </div>
    `).join('');
}

// 显示艺术品详情
function showArtDetail(artworkId) {
    // 查找对应的艺术品
    currentArtwork = artworksData.find(art => art.artwork_id === artworkId);
    if (!currentArtwork) {
        alert('未找到该艺术品信息');
        return;
    }
    
    // 更新详情页数据
    document.getElementById('art-main-img').src = `https://picsum.photos/600/800?random=${currentArtwork.artwork_id}`;
    document.getElementById('art-name').textContent = currentArtwork.title;
    document.getElementById('art-description').textContent = currentArtwork.description || '暂无详细描述';
    document.getElementById('art-price').textContent = `¥${parseFloat(currentArtwork.price).toFixed(2)}`;
    
    // 模拟其他信息（实际项目中应从后端获取完整数据）
    document.getElementById('art-category').textContent = getRandomCategory();
    document.getElementById('art-era').textContent = getRandomEra();
    document.getElementById('art-size').textContent = getRandomSize();
    document.getElementById('art-material').textContent = getRandomMaterial();
    document.getElementById('art-background').textContent = '该作品创作于艺术家创作生涯的鼎盛时期，具有很高的艺术价值和收藏价值。';
    document.getElementById('artist-link').textContent = currentArtwork.creator;
    document.getElementById('seller-name').textContent = '艺术收藏馆_' + (currentArtwork.owner_id % 1000);
    
    // 生成模拟溯源记录
    generateTraceRecords(currentArtwork.artwork_id);
    
    // 显示详情页
    showBuyerPage('detail');
}

// 切换主图
function changeMainImg(src) {
    document.getElementById('art-main-img').src = src.replace('120/120', '600/800');
}

// 生成模拟溯源记录
function generateTraceRecords(seed) {
    const traceContainer = document.getElementById('trace-container');
    const traceTypes = ['创作完成', '首次展览', '收藏记录', '鉴定记录', '拍卖记录', '交易记录'];
    const descriptions = [
        '艺术家完成该作品创作，签署姓名及日期',
        '在国家美术馆进行首次公开展出，引起广泛关注',
        '被私人收藏家收购，纳入私人收藏',
        '经艺术品鉴定机构认证，确认为真迹',
        '在国际艺术品拍卖会上以高价成交',
        '通过正规渠道完成所有权转移'
    ];
    
    // 生成3-5条溯源记录
    const recordCount = 3 + (seed % 3);
    let html = '';
    
    for (let i = 0; i < recordCount; i++) {
        const date = new Date();
        date.setFullYear(2020 + i);
        date.setMonth(i * 2);
        
        html += `
        <div class="flex">
            <div class="mr-4 flex flex-col items-center">
                <div class="w-3 h-3 rounded-full bg-indigo-600"></div>
                ${i < recordCount - 1 ? '<div class="w-0.5 h-full bg-gray-200 mt-1"></div>' : ''}
            </div>
            <div>
                <p class="font-medium text-indigo-600">${traceTypes[i % traceTypes.length]}</p>
                <p class="text-gray-500 text-sm mt-1">事件时间：${formatDate(date)}</p>
                <p class="text-gray-600 mt-2">${descriptions[i % descriptions.length]}</p>
                ${i === 0 ? '<button class="mt-2 text-indigo-600 text-sm hover:underline">查看证书 <i class="fa fa-external-link text-xs"></i></button>' : ''}
            </div>
        </div>
        `;
    }
    
    traceContainer.innerHTML = html;
}

// 获取交易记录
async function fetchTransactions() {
    // 实际项目中应调用后端接口获取当前用户的交易记录
    // 这里使用模拟数据
    transactionsData = generateMockTransactions();
    renderTransactions(transactionsData);
}

// 渲染交易记录
function renderTransactions(transactions) {
    const tableBody = document.getElementById('transactions-table-body');
    const pagination = document.getElementById('pagination');
    const totalRecords = document.getElementById('total-records');
    
    if (transactions.length === 0) {
        tableBody.innerHTML = `
            <tr>
                <td colspan="7" class="px-4 py-8 text-center text-gray-500">
                    <i class="fa fa-exchange text-2xl mb-2 block"></i>
                    暂无交易记录
                </td>
            </tr>
        `;
        pagination.classList.add('hidden');
        return;
    }
    
    // 显示分页控件
    pagination.classList.remove('hidden');
    totalRecords.textContent = transactions.length;
    document.getElementById('last-shown').textContent = Math.min(5, transactions.length);
    
    // 生成交易记录HTML
    tableBody.innerHTML = transactions.slice(0, 5).map(transaction => `
        <tr class="border-t">
            <td class="px-4 py-3">${transaction.id}</td>
            <td class="px-4 py-3">
                <div class="flex items-center">
                    <img src="https://picsum.photos/60/60?random=${transaction.artworkId}" alt="${transaction.artworkName}" class="w-10 h-10 object-cover rounded mr-2">
                    <span>${transaction.artworkName}</span>
                </div>
            </td>
            <td class="px-4 py-3">${transaction.seller}</td>
            <td class="px-4 py-3">${formatDate(transaction.time)}</td>
            <td class="px-4 py-3">¥${transaction.amount.toFixed(2)}</td>
            <td class="px-4 py-3">
                <span class="${getStatusClass(transaction.status)}">${getStatusText(transaction.status)}</span>
            </td>
            <td class="px-4 py-3">
                ${getActionButtons(transaction.id, transaction.status)}
            </td>
        </tr>
    `).join('');
    
    // 生成页码
    generatePageNumbers(Math.ceil(transactions.length / 5));
}

// 筛选交易记录
function filterTransactions(status) {
    let filtered = transactionsData;
    if (status !== 'all') {
        filtered = transactionsData.filter(t => t.status === status);
    }
    renderTransactions(filtered);
}

// 生成页码
function generatePageNumbers(totalPages) {
    const pageNumbersContainer = document.getElementById('page-numbers');
    pageNumbersContainer.innerHTML = '';
    
    for (let i = 1; i <= totalPages; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.className = `relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium ${i === 1 ? 'bg-indigo-50 text-indigo-600' : 'text-gray-700 hover:bg-gray-50'}`;
        pageBtn.textContent = i;
        pageBtn.onclick = () => {
            // 切换页码逻辑
            document.querySelectorAll('#page-numbers button').forEach(btn => {
                btn.className = 'relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50';
            });
            pageBtn.className = 'relative inline-flex items-center px-4 py-2 border border-gray-300 bg-indigo-50 text-sm font-medium text-indigo-600';
            document.getElementById('current-page').textContent = i;
        };
        pageNumbersContainer.appendChild(pageBtn);
    }
}

// 辅助函数：格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 辅助函数：获取状态文本
function getStatusText(status) {
    const statusMap = {
        'pending_payment': '待付款',
        'pending_delivery': '待收货',
        'completed': '交易完成',
        'cancelled': '已取消'
    };
    return statusMap[status] || status;
}

// 辅助函数：获取状态样式
function getStatusClass(status) {
    const classMap = {
        'pending_payment': 'bg-yellow-100 text-yellow-800 text-xs px-2 py-1 rounded',
        'pending_delivery': 'bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded',
        'completed': 'bg-green-100 text-green-800 text-xs px-2 py-1 rounded',
        'cancelled': 'bg-gray-100 text-gray-800 text-xs px-2 py-1 rounded'
    };
    return classMap[status] || 'bg-gray-100 text-gray-800 text-xs px-2 py-1 rounded';
}

// 辅助函数：获取操作按钮
function getActionButtons(orderId, status) {
    switch(status) {
        case 'pending_payment':
            return `
                <button class="text-indigo-600 hover:text-indigo-800 mr-3" onclick="payOrder('${orderId}')">付款</button>
                <button class="text-red-600 hover:text-red-800" onclick="cancelOrder('${orderId}')">取消</button>
            `;
        case 'pending_delivery':
            return `
                <button class="text-green-600 hover:text-green-800 mr-3" onclick="confirmReceipt('${orderId}')">确认收货</button>
                <button class="text-indigo-600 hover:text-indigo-800" onclick="viewOrderDetail('${orderId}')">查看详情</button>
            `;
        case 'completed':
            return `
                <button class="text-indigo-600 hover:text-indigo-800 mr-3" onclick="viewOrderDetail('${orderId}')">查看详情</button>
                <button class="text-gray-600 hover:text-gray-800" onclick="viewTrace('${orderId}')">查看溯源</button>
            `;
        case 'cancelled':
            return `
                <button class="text-indigo-600 hover:text-indigo-800" onclick="viewOrderDetail('${orderId}')">查看详情</button>
            `;
        default:
            return '';
    }
}

// 辅助函数：生成随机艺术品类别
function getRandomCategory() {
    const categories = ['绘画', '雕塑', '书法', '陶瓷', '摄影', '装置艺术'];
    return categories[Math.floor(Math.random() * categories.length)];
}

// 辅助函数：生成随机年代
function getRandomEra() {
    const eras = ['古代', '近代', '现代', '当代'];
    return eras[Math.floor(Math.random() * eras.length)];
}

// 辅助函数：生成随机尺寸
function getRandomSize() {
    const sizes = ['40×50cm', '60×80cm', '100×120cm', '30×40cm', '80×100cm'];
    return sizes[Math.floor(Math.random() * sizes.length)];
}

// 辅助函数：生成随机材质
function getRandomMaterial() {
    const materials = ['布面油画', '宣纸水墨', '青铜', '陶瓷', '大理石', '数码版画'];
    return materials[Math.floor(Math.random() * materials.length)];
}

// 辅助函数：生成模拟交易数据
function generateMockTransactions() {
    const statuses = ['pending_payment', 'pending_delivery', 'completed', 'cancelled'];
    const artworks = artworksData.length > 0 ? artworksData : [
        {title: '《山水图》', artwork_id: 101, price: 28000},
        {title: '《静物写生》', artwork_id: 102, price: 15000},
        {title: '《城市印象》', artwork_id: 103, price: 32000},
        {title: '《人物肖像》', artwork_id: 104, price: 45000},
        {title: '《抽象系列》', artwork_id: 105, price: 22000}
    ];
    
    return Array.from({length: 8}, (_, i) => {
        const date = new Date();
        date.setDate(date.getDate() - i * 3);
        
        const artwork = artworks[i % artworks.length];
        const status = i < statuses.length ? statuses[i] : statuses[Math.floor(Math.random() * statuses.length)];
        
        return {
            id: `TRA${new Date().getFullYear()}${(i + 100).toString().slice(1)}`,
            artworkId: artwork.artwork_id,
            artworkName: artwork.title,
            seller: `艺术机构${i + 1}`,
            time: date,
            amount: artwork.price,
            status: status
        };
    });
}

// 交易相关操作函数
function payOrder(orderId) {
    if(confirm(`确定要支付订单 ${orderId} 吗？`)) {
        // 实际项目中调用后端支付接口
        alert(`订单 ${orderId} 支付成功！`);
        // 更新交易状态
        const transaction = transactionsData.find(t => t.id === orderId);
        if (transaction) {
            transaction.status = 'pending_delivery';
            renderTransactions(transactionsData);
        }
    }
}

function cancelOrder(orderId) {
    if(confirm(`确定要取消订单 ${orderId} 吗？取消后将无法恢复。`)) {
        // 实际项目中调用后端取消订单接口
        alert(`订单 ${orderId} 已取消`);
        // 更新交易状态
        const transaction = transactionsData.find(t => t.id === orderId);
        if (transaction) {
            transaction.status = 'cancelled';
            renderTransactions(transactionsData);
        }
    }
}

function confirmReceipt(orderId) {
    if(confirm(`确定已收到订单 ${orderId} 的商品吗？`)) {
        // 实际项目中调用后端确认收货接口
        alert(`已确认收到订单 ${orderId} 的商品，交易完成！`);
        // 更新交易状态
        const transaction = transactionsData.find(t => t.id === orderId);
        if (transaction) {
            transaction.status = 'completed';
            renderTransactions(transactionsData);
        }
    }
}

function viewOrderDetail(orderId) {
    alert(`查看订单 ${orderId} 的详情`);
    // 实际项目中跳转到订单详情页
}

function viewTrace(orderId) {
    alert(`查看订单 ${orderId} 对应的艺术品溯源信息`);
    // 实际项目中跳转到溯源页面
}

// 加入收藏
function addToCollection(artworkId) {
    const artwork = artworksData.find(art => art.artwork_id === artworkId);
    if (artwork) {
        alert(`已将《${artwork.title}》加入收藏`);
    }
}

// 筛选艺术品
function filterArtworks() {
    // 实际项目中根据筛选条件过滤艺术品
    alert('筛选功能已触发，实际项目中会根据选择的条件过滤艺术品');
}
</script>
</body>
</html>